<?php


namespace app\api\controller\v1;


use app\api\model\BatteryChangeOrderModel;
use app\api\model\BikeModel;
use app\common\controller\UserBaseController;
use app\common\library\DLock;

class BcorderController extends UserBaseController
{
    function submitAction()
    {
        $this->paramlist = array(
            'token' => 'string',
            'bike_id' => 'string',
            'user_coordinate' => 'floatarray',
            'bluetooth' => ['optint', 0],
        );

        $this->check_params();
        $this->check_token();

        $lock = new DLock($this->argv['bike_id'], 60);

        $bike_info = (new BikeModel())->get_info_by_id($this->argv['bike_id']);
        if (empty($bike_info)) {
           $this->throw_myexception(X_ERROR, "bike not found!");
        }

        if ($bike_info['bus_state'] != 0) {
            $this->throw_myexception(X_ERROR, "车辆使用中,请结束当前业务后重试！");
        }

        $ret = (new BatteryChangeOrderModel())->submit($this->city_id, $bike_info, $this->argv['bluetooth']);
        if ($ret[0] != 0) {
            $this->throw_myexception($ret[0], $ret[1]);
        }
        $this->resp['info'] = $ret[2];
    }

    function finishAction()
    {
        $this->paramlist = array(
            'token' => 'string',
            'order_id' => 'string',
            'user_coordinate' => 'floatarray',
            'city_id' => 'optstring',
        );

        $this->check_params();
        $this->check_token();
        $lock = new DLock($this->argv['order_id'], 60);

        $info = (new BatteryChangeOrderModel())->finish($this->city_id, $this->argv['order_id']);
        $this->resp['info'] = $info;
    }

    function listAction()
    {
        $this->paramlist = array(
            'token' => 'string',
            'order_state' => 'optint',
            'battery_increment_upper' => 'optint',
            'battery_increment_lower' => 'optint',
            'increment' => 'optint',
            'pno' => 'int',
            'psize' => 'int',
            'user_id' => 'optstring',
            'bike_id' => 'optstring',
            'is_order_finished' => 'optint',
            'sk' => 'optstring',
            'start_time' => 'optdatetime',
            'end_time' => 'optdatetime',
        );

        $this->check_params();
        $this->check_token();

        $list = ((new BatteryChangeOrderModel()))->query_list($this->city_id, $this->argv, $this->argv['pos'], $this->argv['limit']);
        $this->resp['list'] = $list;

        if (empty($list)) {
            $this->resp['total'] = 0;
        } else {
            $this->resp['total'] = count($list);//hisql::query_count();
        }
    }
}